#!/bin/bash
#
# The all-in-one administrator's script. It contains the following 
# features:
#
# Database Initialization:
#
# Creates a data model suitable for the hosting of articles in a blog, 
# in which case I will use it for my own self-hosting purposes. Uses SQLite
#
# Article publishing:
#
# Enables you to publish a new article, automatically connecting you to the
# vim text editor (:D) and stamping the published date on it.
#
# Article deleting and editing:
#
# Enables you to edit or delete an existing article.
#
# Note on choice of editor:
#
# The default text editor of this app is vim because it's my favorite and 
# pretty much ubiquitous on any unix-ish system (for which this engine is
# intended). If you would like to use another editor, change the EDITOR line
# to the editor of your choice.
#
#    Copyright 2015 K. Zimmermann - https://notabug.org/kzimmermann
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# This is the editor that you will be using to write/edit your posts:
EDITOR="vim"

# Change this to the name of whatever database file you want (leave the 
# .db extension, though), like a salt:
db="main.db"

# Dates must be something that `date' can understand. I personally use the
# YYYY-MM-DD format because it's the most readable one IMO.
DATEFORMAT="%Y-%m-%d"

#-- Functions --#
initialize() {
    sqlite3 $db <<-EOF
    CREATE TABLE IF NOT EXISTS articles (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT,
        body TEXT,
        pubdate TEXT,
        pageviews INTEGER
    );
EOF
    chmod 644 $db
}

publish() {
    printf "Enter a title for the post: "
    read title
    if [[ "$EDITOR" == "vim" ]]; then
        $EDITOR -c 'set linebreak' -c 'set wrap' .temppub
    else
        $EDITOR .temppub
    fi
    # This is required to clean evil quotation marks:
    cat .temppub | sed 's/\"/\&quot;/g' > .cleanpub
    sqlite3 $db <<-EOF  
    INSERT INTO articles (title, body, pubdate, pageviews)
    VALUES
        ("$title", "$(cat .cleanpub)", "$(date +$DATEFORMAT)", 0)
    ;
EOF
    [[ $? -eq 0 ]] && rm .temppub .cleanpub || echo "Error inserting into database. Please try again."
}

edit() {
    printf "Which post ID would you like to edit? "
    read id
    title=$(sqlite3 $db "SELECT title FROM articles WHERE id=$id")
    if [ -z "$title" ]
    then
        echo "This post doesn't exist."
    else
        printf "Edit '$title'? (y/n) "
        read decision
        if [[ "$decision" != "y" ]]
        then
            echo "Aborted."
        else
            printf "Enter a new title for the post (leave blank for no change): "
            read newtitle
            if [[ -z "$newtitle" ]]
            then
                newtitle=$title
            fi
            # Extract the text content in to an external file:
            sqlite3 $db "SELECT body FROM articles WHERE id=$id" > .temppub
            if [[ "$EDITOR" == "vim" ]]; then
                $EDITOR -c 'set linebreak' -c 'set wrap' .temppub
            else
                $EDITOR .temppub
            fi
            cat .temppub | sed 's/\"/\&quot;/g' > .cleanpub
            sqlite3 $db <<-EOF  
            UPDATE articles 
            SET 
                title="$newtitle",
                body="$(cat .cleanpub)", 
                pubdate="$(date +$DATEFORMAT)"
            WHERE id=$id
            ;
EOF
            [[ $? -eq 0 ]]  && rm .temppub .cleanpub || echo "Error inserting into database. Please try again."
        fi
    fi
}

delete() {
    printf "Which post ID would you like to delete? "
    read id
    title=$(sqlite3 $db "SELECT title FROM articles WHERE id=$id")
    if [ -z "$title" ]
    then
        echo "This post doesn't exist."
    else
        printf "Proceed with deleting '$title'? (y/n) "
        read decision
        if [[ "$decision" != "y" ]]
        then
            echo "aborted."
        else
            sqlite3 $db "DELETE FROM articles WHERE id=$id"
            echo "Post deleted"
        fi
    fi
}

#-- /Functions --#

case "$1" in
    "init" ) initialize;;
    "post" ) publish;;
    "edit" ) edit;;
    "delete") delete ;;
    "-h" | "--help" ) echo "options are 'init', 'post', 'edit', 'delete'";;
    * ) echo "Error: missing arguments"
    exit 1
    ;;
esac
